<script setup>
/**
 * @name 数字人批量合成记录抽屉
 */
import { reactive, computed, ref, watch, onMounted, nextTick } from 'vue'

import {
  SaveOutlined,
  FontColorsOutlined,
  EyeOutlined,
  EllipsisOutlined,
  DownOutlined
} from "@ant-design/icons-vue";

import { Form, message, Empty, Modal } from "ant-design-vue";
import request from "@/common/utils/request";

// 视频文件
import MaterialsModule from "@/views/shotstack/components/MaterialsModule/index.vue";
const materials = ref(null);

// 数字人字幕生成组件
import subtitleCreatDialog from '@/views/shotstack/digitalHuman/AIdigitalHumanCreatVideo/Components/subtitleCreatDialog.vue'
const subtitleCreatDialogRef = ref()

// 视频预览组件
import viewVideo from "@/views/shotstack/components/dialogComponent/viewVideo.vue";
const viewVideoRef = ref();

// 字幕视频列表
import HaveTexthumanVideo from './haveTexthumanVideo.vue'
const HaveTexthumanVideoRef = ref()

import { useRouter } from "vue-router";
const router = useRouter();

const props = defineProps({
  // 筛选过滤 status列表
  statusOptions: {
    type: Array,
    default: () => []
  } 
})

const state = reactive({
  visible: false,

  checkAll: false,

  // 保存视频弹窗
  isFlaking: false,
  saveVisible: false,

  // 预览视频弹窗
  viewVisible: false,
  videoUrl:'',

  // 视频列表
  videoArr: [],

  // 预览的组
  viewItem: null,

  // 筛选状态
  status: 'all',

  current:0
})

// 所有状态正常的, id列表
const normalStatusIds = computed(() => {
  const arr = state.videoArr.filter(item => item.status == 3)
  const ids = arr.map(item => item.id)
  return ids || []
})

// 勾选的视频id
const selectIds = ref([])

// 根据用户筛选的状态 过滤列表
const fitlerList = computed(() => {
  let arr = state.videoArr
  if (state.status != 'all') {
    arr = state.videoArr.filter(item => item.status == state.status)
  }
  return arr
})

const selectChange = () => {
  // selectIds.value = []
}

// 是否是批量上传
const saveListFlage = ref(false)

// 上传的类型
const upload_from = ref('')

const statusColor = (status) => {
  switch (status) {
    case 1:
      return "orange";
    case 2:
      return "blue";
    case 3:
      return "green";
    case 4:
      return "red";
    case 5:
      return "pink";
    case 6:
      return "purple";
    case 7:
      return "cyan";
  }
};

// 勾选的视频
const selects = computed(() => {
  const arr = state.videoArr.filter(item => selectIds.value.includes(item.id))
  return arr
})

// 保存视频
const handleSave = async (item, type) => {
  state.saveItem = JSON.parse(JSON.stringify(item));
  // 关闭批量上传开关
  saveListFlage.value = false
  if (type == "material") {
    // 保存到素材库
    state.isFlaking = false;
    state.saveVisible = true;
    upload_from.value = 'backend'
  } else if (type == "complete") {
    // 保存到成片
    state.isFlaking = true;
    state.saveVisible = true;
    upload_from.value = 'shotstack'

  } else {
    item.downloading = true;
    // 下载
    const response = await fetch(item.video_url); // 获取视频链接
    const blob = await response.blob(); // 将响应转为 Blob
    const url = window.URL.createObjectURL(blob); // 创建一个 blob URL

    const link = document.createElement("a");
    link.href = url; // 设置 href 为 blob URL
    link.download = "video.mp4"; // 可选，设置下载时的文件名
    document.body.appendChild(link);
    link.click(); // 模拟点击下载
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url); // 清理
    item.downloading = false;
  }
};

// 批量上传数组
const filterNotUpdate = ref([])

// 拿到选择的文件夹等信息
const selfRequest = async (data) => {
  console.log(data,'保存到素材库弹窗返回结果');  

  let params

// 批量保存
  if (saveListFlage.value) {
     params = {
      mediaData: filterNotUpdate.value.map((item) => {
        return {
            merchant_folder_statck_id: data?.merchant_folder_statck_id,
            digital_id: item?.id,
          group_detail_id: item.detail_id,
          upload_from: upload_from.value
        }
      })
    };
  } else {
     params = {
      mediaData: [{
            merchant_folder_statck_id: data?.merchant_folder_statck_id,
            digital_id:  state.saveItem.id,
            group_detail_id: state.saveItem.detail_id,
            upload_from: upload_from.value
      }]
    };
  }

  console.log(params,'批量保存参数');
  
    // 保存到素材 或成片库
    try {
    const res = await request.post(
      "/work_ai",
      "/digital/human/video/moreAddMedia",
      params
    );
      if (res?.code && res.code != 1000) throw new Error(res.msg);
      message.success("保存成功");
      console.log(res, "保存成功");
    
      getGroupInfo()

  } catch (error) {
    message.error(error.message || "保存失败");
  } finally {
      materials.value.stopLoding();
      state.saveVisible = false;
  }
};

// 删除某项视频
const delItem = (data) => {
  Modal.confirm({
    title: "确定要删除该视频吗?",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    cancelText: "取消",
    onOk: async () => {
      try {
        const res = await request.del("/work_ai", "/digital/human/video/delete", { id: data.id });
        message.success('删除成功')
             getHumanVideoList();
        // 假设这里需要根据响应做进一步处理
      } catch (error) {
        // 错误处理
        console.error("删除失败:", error);
      }
    },
  });
};


// 预览视频 实例
const videoRef = ref()

//查看视频
const toviewVideo = (url) => {
  if (url) {
    state.videoUrl = url
    state.viewVisible = true
    nextTick(() => {
      videoRef.value && (videoRef.value.currentTime = 0)
      videoRef.value && videoRef.value.play()
    })
  }
};

// 关闭 暂停视频播放
watch(() => state.viewVisible, (nv, ov) => {
  if (!nv) {
      videoRef.value && videoRef.value.pause()
  }
})

// 生成字幕
const creatSubtitle = (item) => {
  console.log(item,'需要生成字幕的项目');
  subtitleCreatDialogRef.value?.open(item)
}

// 勾选视频
const selectItem = (item) => {
  // 没有合成成功, 不允许交互
  const index = selectIds.value.findIndex(ele => ele == item?.id)
  if (item?.status != 3) {
    index != -1 && selectIds.value.splice(index, 1)
    return
  }

  if (index == -1) {
    selectIds.value.push(item?.id) 
  } else {
    selectIds.value.splice(index, 1)
  }

  state.checkAll = state.videoArr.length == selectIds.value.length;
};

// 全选
const checkAllChange = () => {
  if (state.checkAll) {
    const arr = state.videoArr.filter(ele => ele.status == 3)
    if(arr.length) {
      selectIds.value = arr.map(ele => ele.id) 
    } else {
      selectIds.value = []
    }
  } else {
    selectIds.value = [] 
  }
};

// 保存到剪辑
const importMontage = async() =>{

  // const arr = selects.value.filter(ele => ele?.is_save_multimedia != 1)
  const arr = JSON.parse(JSON.stringify(selects.value))
  if (arr.length) {
    filterNotUpdate.value = arr
    // 保存到素材库
    state.isFlaking = false;
    state.saveVisible = true;
    // 开启批量上传
    saveListFlage.value = true
    upload_from.value = 'backend'
  }
}

const importDoneMaterial = () => {
  // const arr = selects.value.filter(ele => ele?.is_save_pieces != 1)
  const arr = JSON.parse(JSON.stringify(selects.value))
  if (arr.length) {
    filterNotUpdate.value = arr
        // 保存到成片
    state.isFlaking = true;
    state.saveVisible = true;
    // 开启批量上传
    saveListFlage.value = true
    upload_from.value = 'shotstack'
  }
}

// 获取组的视频信息
const getGroupInfo = async () => {
  const res = await request.get(
    "/work_ai",
    "/digital/human/video/group/groupInfo",
    { group_id: state.viewItem?.id }
  );

  console.log(res, '查询的结果');
  // .filter(ele => ele.status == 3)
  state.videoArr = res.result?.human_video_group_detail
  console.log(state.videoArr, '预览item一组');

}

const toMontage = () => {
  router.push({
    name: 'mixedCutCreat',
    query:{
      materialGroupId: state.viewItem?.id,
      type: 0,
      viewType:2
    }
  })
}

const open = (item) => {
  console.log(item,'是啥??????');
  state.viewItem = JSON.parse(JSON.stringify(item))
  // 过滤出成功的项
  getGroupInfo()
  state.visible = true 
}
const close = () => {
  state.visible = false 
  state.checkAll = false
  selectIds.value = []
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <a-drawer
    v-model:visible="state.visible"
    :destroyOnClose="true"
    class="custom-class"
    style="color: red"
    placement="right"
    :style="{
      'min-width': visible ? '1000px' : 0,
    }"
    :bodyStyle="{
      paddingTop: 0,
      color: '#42464e',
    }"
    :closable="false"
    :maskClosable="false"
    :keyboard="true"
    width="1000px"
  >
    <slot name="title">
      <div class="title_box">
        <h2> 字幕合成预览 </h2>
      </div>
    </slot>
    <div class="content">

      <div class="steps_box">
        <a-steps
                v-model:current="state.current"
                type="navigation"
                size="small"
                @change="onChange"
              >
                <a-step
                  title="编辑字幕 "
                  sub-title="获取字幕并编辑"
                  status="finish"
                  description=""
                />
                <a-step
                  title="字幕成片"
                  sub-title="字幕成片列表"
                  status="wait"
                  description=""
                />
              </a-steps>
      </div>

      <template v-if="state.current == 0">
        <div class="title_controls">
          <a-checkbox v-model:checked="state.checkAll" @change="checkAllChange"
            >全选</a-checkbox>
  
          <div class="top_btns">
              <!-- 状态筛选 -->
              <a-select
                v-if="false"
               v-model:value="state.status"
               :size="size"
               style="width: 200px"
               :options="props.statusOptions"
               @change="selectChange"
             ></a-select>
            <!-- <a-button type="primary" :disabled="!selects.length">保存到素材库</a-button>
            <a-button type="primary" :disabled="!selects.length">保存到成片库</a-button> -->
            <a-dropdown>
            <template #overlay>
              <a-menu :disabled="!selects.length">
                <a-menu-item key="1" @click="importMontage">保存到素材库</a-menu-item>
                <a-menu-item key="2" @click="importDoneMaterial">保存到成片库</a-menu-item>
              </a-menu>
            </template>
            <a-button type="primary" :disabled="!selects.length">
              保存到 <DownOutlined /> 
            </a-button>
          </a-dropdown>
  
          </div>
        </div>
  
        <div class="cart_list" v-if="state.videoArr.length">
            <div @click="selectItem(item)" :class="{'select_item': selectIds.includes(item.id)}" class="cart_item"  v-for="item in fitlerList" :key="item.id">
              <a-tag class="status_tag" :color="statusColor(item.status)">
                <!-- style="font-weight: lighter;" -->
                <span>（{{ item.id }}）</span>
                  {{item.status_txt}}
                  </a-tag>
  
                  <div class="edit_ellip">
                    <a-popover :title="null" placement="bottom">
                      <template #content>
                  <div style="display: flex; flex-direction: column;" v-if="item.status == 3 || item.isDel == 1">
                    <!-- :disabled="item.status != 3" -->
                    <a-button type="link"  v-if="item.status == 3"  :loading="item.downloading"
                    @click.stop="handleSave(item, 'down')">下载视频</a-button>
                    <!-- <a-button type="link"  v-if="item.status == 3"
                    @click="listenVoice(item)">试听音频</a-button> -->
                  <!-- <a-button type="link"   v-if="item.isDel == 1" 
                    @click.stop="delItem(item, 'down')">删除视频</a-button> -->
     
                    </div>
                  </template>
                  <div class="ellips_box">
                    <EllipsisOutlined v-if="item.status == 3 || item.isDel == 1"></EllipsisOutlined>
                  </div>
                  </a-popover>
                  </div>
  
              <div class="cart_main">
                <EyeOutlined v-if="item?.status != 0" @click.stop="toviewVideo(item.video_url)" class="EyeOutlined"></EyeOutlined>
  
                <!-- 
                  v-if="item?.status == 0" 
                 -->
                <a-button 
                v-if="false"
                :loading="queryResultLoading"
                type="primary" class="query_res" 
                @click.stop="debounceQueryResult(item)">手动查询结果</a-button>
  
                <template v-if="item?.cover_url">
                      <img :src="item.cover_url" alt="" />
                    </template>
                <template v-else-if="item?.video_url">
                  <video :src="item.video_url"></video>
                </template>
                <template v-else>
                  <div class="empty_box">
                    <!-- 暂无封面或视频 -->
                    <a-empty description="暂无封面或视频" :image="Empty.PRESENTED_IMAGE_SIMPLE" style="margin: 0 auto"/>
                  </div>
                </template>
  
                <div class="item_name_box" v-if="item.name">
                  <span class="item_name">{{ item.name}}</span>
                </div>
              </div>
              <div class="cart_bottom">
                <div class="msg_box" >
  
                  <!-- <template v-if="item?.is_subtitles == 1">
                    <a-tooltip placement="top">
                      <template #title>
                        <span>该视频已生成字幕</span>
                      </template>
                      <a-button :disabled="true"  style="padding: 0;" type="link">
                        <span style="display: flex; align-items: center; gap: 1px; font-weight: bold;">
                          <FontColorsOutlined style="font-size: 14px;"/>
                          生成字幕
                        </span>
                        </a-button>
                    </a-tooltip>
                  </template>
  
                  <template v-else>    -->
                    <a-button  style="padding: 0;" type="link"   
                    :disabled="item.status != 3"
                    @click.stop="creatSubtitle(item)">
                  <span style="display: flex; align-items: center; gap: 1px; font-weight: bold;">
                    <FontColorsOutlined style="font-size: 14px;"/>
                    生成字幕
                  </span>
                  </a-button>
                  <!-- </template> -->
                  
  
  
                  <a-popover :title="null" placement="top" :getPopupContainer="(target) => {
                    return target.parentNode;
                  }">
                    <template #content>
                      <div style="display: flex; flex-direction: column;">
                        <a-button type="link" :disabled="item.status != 3" 
                      @click.stop="handleSave(item, 'material')">保存到素材库</a-button>
                    <a-button type="link" :disabled="item.status != 3" 
                      @click.stop="handleSave(item, 'complete')">保存到成片库</a-button>
                      </div>
                    </template>
                    <a-button :disabled="item.status != 3" type="link" style="padding: 0;">      
                      <span style="display: flex; align-items: center; gap: 2px; font-weight: bold;">
                        <SaveOutlined style="font-size: 14px;"></SaveOutlined>
                    保存到
                  </span>
                </a-button>
                  </a-popover>
  
                </div>
              </div>
            </div>
          </div>
  
          <div style="display: flex; align-items: center; padding: 20px 0; flex: 1;" v-else>
            <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" style="margin: 0 auto"/>
          </div>
      </template>

      <template v-else>
        <!-- 带字幕的视频列表 -->
        <HaveTexthumanVideo ref="haveTexthumanVideoRef"
        :normalStatusIds="normalStatusIds"
        @viewVideo="toviewVideo"
        ></HaveTexthumanVideo>
      </template>


    </div>
    <template #footer>
      <div class="bottom_btn">
        <a-button style="margin-right: 15px" @click="close"
          >取消</a-button
        >
        <a-button type="primary" @click="close"
          >确定</a-button
        >
      </div>
    </template>
  </a-drawer>

  <!-- 视频预览 -->
  <viewVideo ref="viewVideoRef"></viewVideo>

  <!-- 素材库 -->
  <MaterialsModule ref="materials" :requestType="true" jobCategory="videoSplit" :data="state.materialData"
    :material_type="'video'" :isFlaking="state.isFlaking" :visible="state.saveVisible" @selfRequest="selfRequest"
    @onCancel="state.saveVisible = false" />

      <!-- 生成字幕弹窗 -->
  <subtitleCreatDialog ref="subtitleCreatDialogRef" @openSubtitleCreat="openSubtitleCreat"></subtitleCreatDialog>


    <!-- 视频预览弹窗 -->
    <a-modal :style="{ border: 'none'}" v-model:visible="state.viewVisible"
  :maskClosable="true" :width="800"
  :zIndex="1000"  :centered="false"
  :closable="true" :keyboard="false">
  <template #title>
    <slot name="title">
        <span>查看视频</span>
    </slot>
  </template>

  <div class="view_content">
    <video :src="state.videoUrl" controls autoplay ref="videoRef" class="is_video">
      </video>
  </div>

  <template #footer>
    <a-button type="primary" @click="state.viewVisible = false">关闭</a-button>
  </template>
</a-modal>
</template>

<style scoped lang="less">
// 发布成片下拉样式
.account_item {
  width: 100px;
  height: 30px;
  display: flex;
  align-items: center;
  padding: 3px, 10px;

  img {
    margin-right: 5px;
    width: 20px;
    height: 20px;
  }
}

// 视频预览弹窗样式
.view_content{
  width: 100%;
    height: 500px;
    display: flex;
    justify-content: center;
    background: #000000;

    video {
        height: 100%;
        width: 100%;
        background: rgb(223, 223, 223);
    }
}

:deep(.ant-spin-container) {
  background-color: #131313;
  overflow: hidden;
}

.title_box {
  padding: 20px 0;

  h2 {
    margin: 0;
    font-weight: 600;
    font-size: 18px;
  }
}

// 整体样式
.content {
  width: 100%;
  height: calc(100% - 68px);
  // height: 100%;
  // padding-top: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  // 头部全选等控制按钮
  .title_controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;

    .top_btns{
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .title_controls_right {
      display: flex;
      gap: 0 10px;
    }
  }

  .cart_list{
    flex: 1;
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;
      gap: 20px 20px;
      overflow-y: auto;
      overflow-x: hidden;
      &::-webkit-scrollbar {
            width: 8px; /* 滚动条的宽度 */
            height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        }
        &::-webkit-scrollbar-thumb {
            background: #888; /* 滑块的背景颜色 */
            border-radius: 10px; /* 滑块的圆角 */

        }
      

      .cart_item{
        background-color: #fff;
        border: 2px solid #eee;
        box-shadow: 0 0 12px rgba(0, 0, 0, 0.06); /* 透明度调低更柔和 */


        position: relative;
        // max-width: 190px;

        &.select_item {
          border-color: var(--ss-primary-color);

        }

        .status_tag{
          position: absolute;
          left: 5px;
          top: 5px;
          z-index: 1;
          font-size: 12px;
          font-weight: bold;
        }
        .edit_ellip{
          position: absolute;
          z-index: 3;
          right: 5px;
          top: 5px;
          font-size: 28px;
          color: #fff;
          line-height: 1;
          font-weight: bold;
          cursor: pointer;

          .ellips_box{
            background: #0000004b;
            padding: 0 5px;
            border-radius: 8px;
          }
        }
        .cart_main{
          height: 280px;
          width: 190px;
          cursor: pointer;
          position: relative;
          overflow: hidden;

                  // name 遮罩层
        .item_name_box{
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          padding: 2px 5px;
          background: #0000004b;
          .item_name{
              color: #fff;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              width: auto;
            }
        }

          img{
            height: 100%;
            width: 100%;
            object-fit: cover;
          }
          video{
            // height: 100%;
            width: 100%;
          }
          .empty_box{
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            // background-color: #00000017;
          }

          &::after{
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          z-index: 2;
          background-color: transparent;
          opacity: 0;
          transition: all .3s;
          height: 100%;
          width: 100%;
        }
          &:hover{
          &::after{
            background-color: #00000056;
            opacity: 1;
          }

          .EyeOutlined{
            opacity: 1;
          }
          .query_res{
            opacity: 1;
          }
        }

        .EyeOutlined{
          position: absolute;
          z-index: 3;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          color: #fff;
          transition: all .3s;
          opacity: 0;
          font-size: 30px;
          &:hover{
            color: var(--ss-primary-color-hover);
          }
        }

        .query_res {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          transition: all 0.3s;
          opacity: 0;
          z-index: 3;
        }

        }
        .cart_bottom{
          width: 100%;
          background-color: #fff;
          padding: 5px 5px;
          font-weight: bold;
          border-top: 1px solid #eee;

          .msg_box{
            display: flex;
            justify-content: space-between;
            align-items: center;


          }
        }
      }
    }
}

// 底部按钮
.bottom_btn {
  padding: 8px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
}
</style>
